package com.zzk.protect.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zzk.protect.common.CommonResult;
import com.zzk.protect.pojo.MedicalRecord;
import com.zzk.protect.service.MedicalRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/medicalRecord")
public class MedicalRecordController {
    @Autowired
    private MedicalRecordService medicalRecordService;
    @PostMapping("/add")
    public CommonResult add(@RequestBody MedicalRecord medicalRecord){
        return CommonResult.success(medicalRecordService.save(medicalRecord));
    }
    @GetMapping("/getByRegistrationId")
    public CommonResult<MedicalRecord> getByRegistrationId(@RequestParam Integer registrationId){
        QueryWrapper<MedicalRecord> qw = new QueryWrapper<>();
        qw.eq("registration_id",registrationId);
        return CommonResult.success(medicalRecordService.getOne(qw));
    }
    @PostMapping("/update")
    public CommonResult update(@RequestBody MedicalRecord medicalRecord){
        return CommonResult.success(medicalRecordService.updateById(medicalRecord));
    }
    @PostMapping("/updateExaminationResult")
    public CommonResult updateExaminationResult(
            @RequestParam Integer registrationId,
            @RequestParam String examinationResult) {
        try {
            // 1. 构建更新条件：通过 registration_id 匹配病历记录
            UpdateWrapper<MedicalRecord> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("registration_id", registrationId); // 关联挂号ID

            // 2. 创建更新实体，设置检验结果字段
            MedicalRecord updateEntity = new MedicalRecord();
            updateEntity.setExaminationResult(examinationResult); // 核心：更新 examination_result 字段

            // 3. 执行更新操作
            boolean success = medicalRecordService.update(updateEntity, updateWrapper);

            // 4. 根据更新结果返回响应
            if (success) {
                return CommonResult.success("检验结果保存成功");
            } else {
                return CommonResult.failed("保存失败，未找到匹配的病历记录（registrationId=" + registrationId + "）");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("保存检验结果时发生错误：" + e.getMessage());
        }
    }
}
